<?php

namespace app\admin\model;

use think\facade\Cache;
use app\common\model\BaseModel as Model;
use Overtrue\Pinyin\Pinyin;

class AuthRule extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 数据自动完成字段
    protected $insert = ['py', 'pinyin'];
    protected $update = ['py', 'pinyin'];
    // 拼音对象
    protected static $pinyin = null;

    public static function onBeforeWrite($row)
    {
        if (isset($_POST['row']) && is_array($_POST['row']) && isset($_POST['row']['condition'])) {
            $originRow = $_POST['row'];
            $row['condition'] = $originRow['condition'] ?? '';
        }
    }

    public static function onAfterWrite($row)
    {
        if (isset($_POST['row']) && is_array($_POST['row']) && isset($_POST['row']['condition'])) {
            Cache::delete('__menu__');
        }
    }


    public function getMenutypeList()
    {
        return ['addtabs' => '选项卡(默认)', 'dialog' => '弹窗', 'ajax' => 'Ajax请求', 'blank' => '链接'];
    }

    public function setPyAttr($value, $data)
    {
        if (isset($data['title']) && $data['title']) {
            return Pinyin::abbr($data['title'])->join('');
        }
        return '';
    }

    public function setPinyinAttr($value, $data)
    {
        if (isset($data['title']) && $data['title']) {
            return Pinyin::permalink($data['title'], '');
        }
        return '';
    }
}
